import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/http/url_helper.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/verify_code_exception_help.widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

class WalletForgotPasswordPage extends StatefulWidget {
  const WalletForgotPasswordPage({super.key});

  @override
  State<WalletForgotPasswordPage> createState() => _WalletForgotPasswordPageState();
}

class _WalletForgotPasswordPageState extends State<WalletForgotPasswordPage> {
  final _smsTextEditingController = TextEditingController();
  final _pwdTextEditingController = TextEditingController();

  bool _isShowEye = false;
  int _countValue = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _smsTextEditingController.addListener(() {
      setState(() {});
    });
    _pwdTextEditingController.addListener(() {
      setState(() {});
    });
  }

  // @override
  // Widget build(BuildContext context) {
  //   var isSelectBtn = _smsTextEditingController.text.isNotEmpty &&
  //       _pwdTextEditingController.text.isNotEmpty;
  //   return Scaffold(
  //       resizeToAvoidBottomInset: false,
  //       appBar: CommWidget.getCommAppbar(context),
  //       body: Container(
  //         width: double.infinity,
  //         height: double.infinity,
  //         color: ColorRes.white,
  //         child: Column(children: [
  //           CommWidget.buildLine(height: 12.w, color: ColorRes.colorf5f7f9),
  //           Expanded(
  //               child: Container(
  //                   padding: EdgeInsets.all(12.w),
  //                   width: double.infinity,
  //                   height: double.infinity,
  //                   child: Column(
  //                     crossAxisAlignment: CrossAxisAlignment.center,
  //                     children: [
  //                       SizedBox(
  //                           height: 50.w,
  //                           child: Row(children: [
  //                             Expanded(
  //                               child: Text(
  //                                 App.instance.userInfo?.phone ?? '',
  //                                 style: TextStyle(
  //                                     color: ColorRes.color333333,
  //                                     fontWeight: FontWeight.bold,
  //                                     fontSize: 16.sp),
  //                               ),
  //                             ),
  //                             GestureDetector(
  //                               onTap: () => _getSms(),
  //                               child: Container(
  //                                   height: 30.w,
  //                                   padding: EdgeInsets.only(
  //                                       left: 10.w, right: 10.w),
  //                                   alignment: Alignment.center,
  //                                   decoration: BoxDecoration(
  //                                       color: ColorRes.colorf8b751,
  //                                       borderRadius: BorderRadius.all(
  //                                           Radius.circular(5.w))),
  //                                   child: Text(
  //                                       _countValue == 0
  //                                           ? '获取验证码'
  //                                           : '$_countValue秒后可重新发送',
  //                                       style: TextStyle(
  //                                           color: ColorRes.colorFFFFFF,
  //                                           fontSize: 13.sp))),
  //                             )
  //                           ])),
  //                       CommWidget.buildLine(),
  //                       SizedBox(
  //                         height: 50.w,
  //                         width: double.infinity,
  //                         child: TextField(
  //                           controller: _smsTextEditingController,
  //                           keyboardType: TextInputType.number,
  //                           inputFormatters: [
  //                             LengthLimitingTextInputFormatter(6),
  //                             FilteringTextInputFormatter.allow(
  //                                 RegExp(r'[0-9a-zA-Z]'))
  //                           ],
  //                           decoration: const InputDecoration(
  //                               hintText: '请输入验证码', border: InputBorder.none),
  //                         ),
  //                       ),
  //                       CommWidget.buildLine(),
  //                       SizedBox(
  //                         height: 50.w,
  //                         width: double.infinity,
  //                         child: Row(
  //                           children: [
  //                             Expanded(
  //                                 child: TextField(
  //                               controller: _pwdTextEditingController,
  //                               keyboardType: TextInputType.number,
  //                               inputFormatters: [
  //                                 LengthLimitingTextInputFormatter(6),
  //                                 FilteringTextInputFormatter.allow(
  //                                     RegExp(r'[0-9a-zA-Z]'))
  //                               ],
  //                               obscureText: !_isShowEye,
  //                               decoration: const InputDecoration(
  //                                   hintText: '请输入新密码',
  //                                   border: InputBorder.none),
  //                             )),
  //                             GestureDetector(
  //                                 onTap: () {
  //                                   _isShowEye = !_isShowEye;
  //                                   setState(() {});
  //                                 },
  //                                 child: ImageLoader.loadAsset(
  //                                     _isShowEye
  //                                         ? 'icon_eye.webp'
  //                                         : 'icon_eye_close.webp',
  //                                     20.w))
  //                           ],
  //                         ),
  //                       ),
  //                       CommWidget.buildLine(),
  //                       SizedBox(
  //                         height: 52.w,
  //                       ),
  //                       CommWidget.buildBtn1('确定', () => _updatePwdBySmsCode(),
  //                           isSelect: isSelectBtn),
  //                       Expanded(
  //                           child: GestureDetector(
  //                               onTap: () => NativeInterface().call(
  //                                   App.instance.serviceInfo?.phone ?? ""),
  //                               child: Column(
  //                                 mainAxisAlignment: MainAxisAlignment.end,
  //                                 crossAxisAlignment: CrossAxisAlignment.start,
  //                                 children: [
  //                                   Row(
  //                                     mainAxisAlignment:
  //                                         MainAxisAlignment.center,
  //                                     children: [
  //                                       Text('  客服电话：',
  //                                           style: TextStyle(
  //                                               color: ColorRes.color666666,
  //                                               fontSize: 12.sp)),
  //                                       Text(
  //                                           App.instance.serviceInfo?.phone ??
  //                                               '',
  //                                           style: TextStyle(
  //                                               color: ColorRes.color0065ff,
  //                                               fontSize: 12.sp)),
  //                                     ],
  //                                   ),
  //                                   Row(
  //                                     mainAxisAlignment:
  //                                         MainAxisAlignment.center,
  //                                     children: [
  //                                       Text('客服工作时间：',
  //                                           style: TextStyle(
  //                                               color: ColorRes.color666666,
  //                                               fontSize: 12.sp)),
  //                                       Text(
  //                                           '工作日${App.instance.serviceInfo?.workingTime ?? ''}',
  //                                           style: TextStyle(
  //                                               color: ColorRes.color666666,
  //                                               fontSize: 12.sp)),
  //                                     ],
  //                                   )
  //                                 ],
  //                               ))),
  //                       SizedBox(
  //                         height: 20.w,
  //                       ),
  //                     ],
  //                   )))
  //         ]),
  //       ));
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        color: ColorRes.white,
        child: Column(
          children: [
            CommWidget.buildLine(height: 12.w, color: ColorRes.colorf5f7f9),
            Expanded(
              child: Container(
                padding: EdgeInsets.all(12.w),
                width: double.infinity,
                height: double.infinity,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    _buildSmsRow(),
                    CommWidget.buildLine(),
                    _buildSmsTextField(),
                    CommWidget.buildLine(),
                    _buildPasswordTextField(),
                    CommWidget.buildLine(),
                    SizedBox(
                      height: 10.w,
                    ),
                    VerifyCodeExceptionHelpWidget(),
                    SizedBox(height: 52.w),
                    _buildSubmitButton(),
                    // Expanded(
                    //   child: GestureDetector(
                    //     onTap: () => NativeInterface().call(
                    //       App.instance.serviceInfo?.phone ?? "",
                    //     ),
                    //     child: _buildServiceInfo(),
                    //   ),
                    // ),
                    // SizedBox(height: 20.w),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取验证码异常帮助
  _getCodeExceptionHelp(String title, String url) async {
    await UrlHelper.loadH5Page(title, url);
  }

  /// 获取验证码栏
  Widget _buildSmsRow() {
    return SizedBox(
      height: 50.w,
      child: Row(
        children: [
          Expanded(
            child: Text(
              App.instance.userInfo?.phone ?? '',
              style: TextStyle(
                color: ColorRes.color333333,
                fontWeight: FontWeight.bold,
                fontSize: 16.sp,
              ),
            ),
          ),
          GestureDetector(
            onTap: () => _getSms(),
            child: Container(
              height: 30.w,
              padding: EdgeInsets.only(left: 10.w, right: 10.w),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: ColorRes.colorf8b751,
                borderRadius: BorderRadius.all(Radius.circular(5.w)),
              ),
              child: Text(
                _countValue == 0 ? '获取验证码' : '$_countValue秒后可重新发送',
                style: TextStyle(
                  color: ColorRes.colorFFFFFF,
                  fontSize: 13.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 输入验证码栏
  Widget _buildSmsTextField() {
    return SizedBox(
      height: 50.w,
      width: double.infinity,
      child: TextField(
        controller: _smsTextEditingController,
        keyboardType: TextInputType.number,
        inputFormatters: [
          LengthLimitingTextInputFormatter(6),
          FilteringTextInputFormatter.allow(RegExp(r'[0-9a-zA-Z]')),
        ],
        decoration: const InputDecoration(
          hintText: '请输入验证码',
          border: InputBorder.none,
        ),
      ),
    );
  }

  /// 输入新密码栏
  Widget _buildPasswordTextField() {
    return SizedBox(
      height: 50.w,
      width: double.infinity,
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _pwdTextEditingController,
              keyboardType: TextInputType.number,
              inputFormatters: [
                LengthLimitingTextInputFormatter(6),
                FilteringTextInputFormatter.allow(RegExp(r'[0-9a-zA-Z]')),
              ],
              obscureText: !_isShowEye,
              decoration: const InputDecoration(
                hintText: '请输入新密码',
                border: InputBorder.none,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _isShowEye = !_isShowEye;
              setState(() {});
            },
            child: ImageLoader.loadAsset(
              _isShowEye ? 'icon_eye.webp' : 'icon_eye_close.webp',
              20.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 提交按钮
  Widget _buildSubmitButton() {
    var isSelectBtn = _smsTextEditingController.text.isNotEmpty && _pwdTextEditingController.text.isNotEmpty;
    return CommWidget.buildRightBtn('确定', () => _updatePwdBySmsCode(), isSelect: isSelectBtn);
  }

  /// 客服
  Widget _buildServiceInfo() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '  客服电话：',
              style: TextStyle(color: ColorRes.color666666, fontSize: 12.sp),
            ),
            Text(
              App.instance.serviceInfo?.phone ?? '',
              style: TextStyle(color: ColorRes.colorMain, fontSize: 12.sp),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '客服工作时间：',
              style: TextStyle(color: ColorRes.color666666, fontSize: 12.sp),
            ),
            Text(
              '工作日${App.instance.serviceInfo?.workingTime ?? ''}',
              style: TextStyle(color: ColorRes.color666666, fontSize: 12.sp),
            ),
          ],
        ),
      ],
    );
  }
// }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    super.dispose();
  }

  /// 启动Timer
  _startTimer() {
    const Duration duration = Duration(seconds: 1);
    cancelTimer();

    _timer = Timer.periodic(duration, (timer) {
      _countValue -= 1;
      print(_countValue);
      if (_countValue <= 0) {
        cancelTimer();
      }
      setState(() {});
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 获取验证码
  _getSms() async {
    if (_countValue > 0) return;
    var phone = App.instance.userInfo?.phone;
    if (phone == null || phone.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.walletRetrievePwdSendSms, urlParams: {
      'phoneNum': phone,
      "purpose": '修改安全码',
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _countValue = 60;
      _startTimer();
    }
    ToastUtils.showToast(context, serviceResult.responseMsg);
  }

  /// 修改密码
  _updatePwdBySmsCode() async {
    // 隐藏键盘
    FocusScope.of(context).unfocus();
    FocusScope.of(context).requestFocus(FocusNode()); // 阻止焦点传递
    var smsCode = _smsTextEditingController.text;
    var pwd = _pwdTextEditingController.text;
    var phone = App.instance.userInfo?.phone ?? '';
    if (smsCode.isEmpty) {
      Fluttertoast.showToast(msg: '请输入验证码');
      return;
    }
    if (pwd.length < 6) {
      Fluttertoast.showToast(msg: '请输入6位纯数字的安全码');
      return;
    }
    var id = App.instance.userInfo?.id;
    if (id == null || id.isEmpty == true) return;
    _countValue = 60;
    var httpRequest = HttpRequest(Api.walletRetrievePwdEditSubmit, urlParams: {
      "userMedicalId": id,
      'safeCode': StringUtils.dartMd5(pwd),
      "code": smsCode,
      "phoneNum": phone,
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    Fluttertoast.showToast(msg: serviceResult.responseMsg ?? "");
    if (serviceResult.success) {
      context.pop();
    }
  }
}
